'use strict';

const Controller = require('egg').Controller;
const OSS = require('ali-oss');
const jwt = require('jsonwebtoken');

const OSSPage = new OSS({
  region: 'oss-cn-beijing',
  accessKeyId: 'LTAI5tM8EcmsJrB5FAvb2Kne',
  accessKeySecret: 'e1KnuO0cVrmV5MqReD85SZvTjP3eGD',
  bucket: '1908abucket',
});

class HomeController extends Controller {
  async index() {
    const { ctx } = this;

    const { authorization } = ctx.request.headers;
    // 获取文件信息
    const file = ctx.request.files[0];

    // 生成随机的图片名称
    const filename = new Date().getTime() + file.filename;

    // 将文件信息保存到oss中
    const data = await OSSPage.put(filename, file.filepath);

    // 将当前登录 用户 的头像更改掉
    const id = jwt.verify(authorization, '1908A');

    // 通过id 更新当前登录人信息
    await this.app.mysql.update('userlist', { id, avatar_url: data.url });

    ctx.body = {
      code: 1,
      data,
    };
  }
}

module.exports = HomeController;
